﻿using UnityEngine;
using UnityEngine.Playables;

public class LerpMoveObjectPlayable : PlayableBehaviour
{
    private GameObject _gameObject;
    private Transform _lerpMoveTo;

    Vector3 _originalPosition;
    private Quaternion _originalRotation;
    private Vector3 _originalScale;

    public void Initialize(GameObject gameObject, Transform lerpMoveTo)
    {
        Debug.Log("Initialize");
        Debug.Log("Initialize = " + gameObject.GetInstanceID());

        _gameObject = gameObject;
        _lerpMoveTo = lerpMoveTo;
    }

    public override void ProcessFrame(Playable playable, FrameData info, object playerData) 
    {
        if (playable.GetTime() <= 0 || _lerpMoveTo == null || _gameObject == null)
            return;

        //直接使用系统自带的Playable Track，添加LerpMoveObjectAsset，在这里是获取不到playerData的
        //通过编写LerpMoveObjectTrack，并在Track进行赋值才可以得到playerData
        //GameObject go = (GameObject)playerData;
        //Debug.Log("ProcessFrame" + go.GetInstanceID());

        _gameObject.transform.position = Vector3.Lerp (_originalPosition, _lerpMoveTo.position, (float)(playable.GetTime() / playable.GetDuration()));
        _gameObject.transform.rotation = Quaternion.Lerp (_originalRotation, _lerpMoveTo.rotation, (float)(playable.GetTime() / playable.GetDuration()));
        _gameObject.transform.localScale = Vector3.Lerp (_originalScale, _lerpMoveTo.localScale, (float)(playable.GetTime() / playable.GetDuration()));
    }

    public override void OnBehaviourPause(Playable playable, FrameData info)
    {
        Debug.Log("OnBehaviourPause");

        if (_gameObject != null)
        {
            _originalPosition = _gameObject.transform.position;
            _originalRotation = _gameObject.transform.rotation;
            _originalScale = _gameObject.transform.localScale;
        }
    }

    public override void OnBehaviourPlay(Playable playable, FrameData info)
    {
        Debug.Log("OnBehaviourPlay");
        if (_gameObject != null)
        {
            _originalPosition = _gameObject.transform.position;
            _originalRotation = _gameObject.transform.rotation;
            _originalScale = _gameObject.transform.localScale;
        }
    }

    //public override void OnGraphStart(Playable playable)
    //{
    //    Debug.Log("OnGraphStart");
    //}

    //public override void OnGraphStop(Playable playable)
    //{
    //    Debug.Log("OnGraphStop");
    //}

    //public override void OnPlayableCreate(Playable playable)
    //{
    //    Debug.Log("OnPlayableCreate");
    //}

    //public override void OnPlayableDestroy(Playable playable)
    //{
    //    Debug.Log("OnPlayableDestroy");
    //}

    //public override void PrepareData(Playable playable, FrameData info)
    //{
    //    Debug.Log("PrepareData");
    //}

}
